<template>
  <div>
    <page-dialog
      :title="dialogInfo.title"
      v-model:visible="shows"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <div class="layui-row">
        <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
          <dialog-table
            :pager="false"
            :check-box="false"
            :tab-index="true"
            v-model:data="tableInfo.data"
            :field-list="tableInfo.fieldList"
            :handle="tableInfo.handle"
          >
            <template v-slot:col-relationName="scope">
              <el-form-item
                :prop="`data.${scope.$index}.relationName`"
                :rules="[
                  {
                    required: scope.$index >= 0,
                    message: '请选择使用部门',
                    trigger: 'blur',
                  },
                ]"
              >
                <el-input
                  v-model="scope.row.relationName"
                  style="width: 100%; margintop: 18px"
                  type="input"
                  :disabled="true"
                  class="not-mongolia"
                  placeholder="请选择使用部门"
                >
                  <template #append>
                    <el-icon @click="openAmortizationDept(scope.$index)"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </template>
            <template v-slot:col-relationValue="scope">
              <el-form-item
                :prop="`data.${scope.$index}.relationValue`"
                :rules="
                  scope.$index >= 0
                    ? [
                        {
                          validator: $validate.positiveScore,
                          trigger: 'blur',
                        },
                      ]
                    : []
                "
              >
                <el-input-number
                  v-model.lazy="scope.row.relationValue"
                  style="width: 100%; margintop: 18px"
                  clearable
                  controls-position="right"
                  :min="0"
                  :precision="2"
                  :max="100"
                />
              </el-form-item>
            </template>
          </dialog-table>
        </el-form>
      </div>
    </page-dialog>
    <select-dept
      v-if="addAssetAmortizationDeptInfo.visible"
      v-model:show-dialog="addAssetAmortizationDeptInfo.visible"
      :query="addAssetAmortizationDeptInfo.query"
      :save-empty="true"
      :check-box="false"
      :highlight-row="true"
      @callback="selectAssetAmortizationDeptCallback"
    />
  </div>
</template>
<script setup>
const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps({
  showDialog: {
    type: Boolean,
    default: false,
  },
})

const tableInfo = ref({
  data: [{ relationName: '', relationId: '', relationValue: 0 }],
  fieldList: [
    {
      label: '使用部门',
      value: 'relationName',
      type: 'slot',
    },
    {
      label: '占比',
      value: 'relationValue',
      type: 'slot',
      labelTip: '总值100%',
    },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '新增行',
        event: addDept,
        show: true,
      },
      {
        label: '删除',
        event: removeDept,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: true,
        ifRender: ifRenderRemoveDept,
      },
    ],
  },
})
const addAssetAmortizationDeptInfo = ref({
  visible: false,
  index: '',
  query: {
    deptAuth: 'id',
    idNotIn: '',
  },
})
const dialogInfo = ref({
  title: '使用部门',
  btLoading: false,
  width: '90%',
  btList: [
    { label: '关闭', event: closeAmortization, show: true },
    {
      label: '保存',
      type: 'primary',
      event: saveAmortization,
      show: true,
    },
  ],
})

const shows = computed({
  get() {
    return props.showDialog
  },
  set(newValue) {
    emits('update:showDialog', newValue) // 更新父组件shows
  },
})

function openAmortizationDept(index) {
  //新增使用部门
  let ids = []
  if (tableInfo.value.data && tableInfo.value.data.length) {
    tableInfo.value.data.forEach((item) => {
      if (item.relationName) {
        ids.push(item.relationId)
      }
    })
  }
  addAssetAmortizationDeptInfo.value.query.idNotIn = ids.toString()
  addAssetAmortizationDeptInfo.value.index = index
  addAssetAmortizationDeptInfo.value.visible = true
}
function selectAssetAmortizationDeptCallback(data) {
  //选择使用部门返回
  let currIndex = addAssetAmortizationDeptInfo.value.index
  if (data && data.id) {
    tableInfo.value.data.forEach((item, index) => {
      if (index === currIndex) {
        item['relationName'] = data.name
        item['relationId'] = data.id
      }
    })
  } else {
    tableInfo.value.data.forEach((item, index) => {
      if (index === currIndex) item['relationName'] = ''
      item['relationId'] = -2
    })
  }
  addAssetAmortizationDeptInfo.value.visible = false
}
function closeAmortization() {
  //关闭使用弹窗
  tableInfo.value.data = [{ relationName: '', relationValue: 0 }]
  shows.value = false
}
function saveAmortization() {
  //保存使用部门
  proxy.$refs['tableForm'].validate((valid) => {
    if (valid) {
      let sumQty = 0
      tableInfo.value.data.forEach((item) => {
        sumQty = proxy.$fn.accAdd(item.relationValue || 0, sumQty)
      })
      if (sumQty !== 100) {
        proxy.$message({
          showClose: true,
          message: `添加的使用部门占比之和必须等于100`,
          type: 'warning',
          duration: 3500,
        })
        return
      }
      emits('callback', tableInfo.value.data)
      closeAmortization()
    }
  })
}
function addDept() {
  //添加使用部门
  tableInfo.value.data.push({
    relationName: '',
    relationValue: 0,
  })
}
function removeDept(row) {
  //删除使用部门
  tableInfo.value.data = tableInfo.value.data.filter((item) => item !== row)
  setTimeout(() => {
    proxy.$refs.tableForm.clearValidate()
  }, 30)
}
function ifRenderRemoveDept() {
  //使用部门列表是否显示删除
  if (tableInfo.value.data.length - 1) {
    return true
  } else {
    return false
  }
}
</script>
